package com.spring.jdbctemplate.application;

import com.spring.jdbctemplate.bean.Employee;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ApplicationJdbcTemplate {

   ApplicationContext context =  new ClassPathXmlApplicationContext("SpringConfig-JdbcTemplate.xml");
    JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
    @Test
    public void testJdbcTemplate(){
        JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
        System.out.println(template);
    }

    //更新一条员工的数据
    @Test
    public void testUpdateEmp(){
        String  sql = "UPDATE employee SET salary = ? WHERE emp_id = ?";
        int update = template.update(sql, 5000, 1);
        System.out.println(update);
    }
    //实现批量插入
    @Test
    public void testInsertBatchEmp(){
        String sql = "INSERT INTO employee(emp_name,salary) VALUES(?,?)";
        List<Object[]> batchArgs = new ArrayList<Object[]>();
        batchArgs.add(new Object[]{"juan",6400});
        batchArgs.add(new Object[]{"juan",6400});
        batchArgs.add(new Object[]{"juan",6400});
        batchArgs.add(new Object[]{"juan",6400});
        batchArgs.add(new Object[]{"juan",6400});
        int[] ints = template.batchUpdate(sql, batchArgs);
        Arrays.toString(ints);
    }

    //查询一条数据
    @Test
    public void testGetForObject(){
        String sql="SELECT emp_id,emp_name,salary FROM employee WHERE emp_id = ?";
        Employee employee = template.queryForObject(sql, new BeanPropertyRowMapper<Employee>(Employee.class), 1);
        System.out.println(employee);
    }
    //查询多条语句
    @Test
    public void testGetList(){
        String sql = "SELECT emp_id,emp_name,salary FROM employee WHERE salary > ?";
        List<Employee> list = template.query(sql, new BeanPropertyRowMapper(Employee.class), 4000);
        for (Employee emp : list){
            System.out.println(emp);
        }
    }
    //查询工资最高的salary
    @Test
    public void testMaxSalary(){
        String sql = "select max(salary) from employee";
        Double maxSal = template.queryForObject(sql, Double.class);
        System.out.println(maxSal);

    }
}
